package com.itsu.mysql.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itsu.interfaces.entity.UserLogin;
import com.itsu.interfaces.service.UserLoginService;
import com.itsu.mysql.mappers.UserLoginMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    UserLoginMapper userLoginMapper;


    @Override
    public void addUserLogin(UserLogin userLogin) {
        userLoginMapper.insert(userLogin);
    }

    @Override
    public Integer findActiveUser(Date start, Date end) {
        QueryWrapper<UserLogin> queryWrapper = new QueryWrapper<>();
        return userLoginMapper.selectCount(queryWrapper.select("DISTINCT user_id")
                .between("login_time", start, end)
        );
    }

    @Override
    public Integer loginUserCount(Date start, Date end) {
        return userLoginMapper.selectCount(Wrappers.lambdaQuery(UserLogin.class)
                .between(UserLogin::getLoginTime, start, end));
    }

    @Override
    public UserLogin findUserByUid(Long uid) {
        return userLoginMapper.selectOne(Wrappers.lambdaQuery(UserLogin.class)
                .eq(UserLogin::getUserId, uid)
                .orderByDesc(UserLogin::getLoginTime)
                .last("limit 1"));
    }

    @Override
    public List<UserLogin> findUser(Date start, Date end) {
        return userLoginMapper.selectList(Wrappers.lambdaQuery(UserLogin.class)
                .between(UserLogin::getLoginTime, start, end)
        );
    }

    @Override
    public Page<UserLogin> pageLoginLogs(Integer page, Integer pageSize, String sub, Long uid) {
        return userLoginMapper.selectPage(new Page<>(page, pageSize),
                Wrappers.lambdaQuery(UserLogin.class)
                        .eq(UserLogin::getUserId, uid)
                        .orderBy(StrUtil.isNotBlank(sub)&&"asc".equalsIgnoreCase(sub), true, UserLogin::getLoginTime)
                        .orderBy(StrUtil.isNotBlank(sub)&&"desc".equalsIgnoreCase(sub), false, UserLogin::getLoginTime));
    }


}
